package com.ozner.cup.Device.Kettle;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.ozner.Kettle.HeatMode;
import com.ozner.Kettle.Kettle;
import com.ozner.Kettle.PreservationMode;
import com.ozner.cup.Bean.Contacts;
import com.ozner.cup.Command.OznerPreference;
import com.ozner.cup.Command.UserDataPreference;
import com.ozner.cup.CupRecord;
import com.ozner.cup.DBHelper.DBManager;
import com.ozner.cup.DBHelper.OznerDeviceSettings;
import com.ozner.cup.Device.DeviceFragment;
import com.ozner.cup.Device.WaterPurifier.WPTempColorUtil;
import com.ozner.cup.Main.MainActivity;
import com.ozner.cup.R;
import com.ozner.cup.UIView.TdsDetailProgress;
import com.ozner.cup.UIView.UIZSeekBarNormal;
import com.ozner.cup.Utils.LCLogUtils;
import com.ozner.cup.Utils.Rotatable;
import com.ozner.device.BaseDeviceIO;
import com.ozner.device.OperateCallback;
import com.ozner.device.OznerDevice;
import com.ozner.device.OznerDeviceManager;
import com.zcw.togglebutton.ToggleButton;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.LinkagePicker;

/**
 * description: KettleFragment
 * autour: ozner_67
 * date: 2017/7/13 9:56
 * e-mail: xinde.zhang@cftcn.com
 */

public class KettleFragment extends DeviceFragment {
    private static final String TAG = "KettleFragment";
    private static final String CUSTOMER_TEMP = "custom_pervation_";
    private static final int HANDLER_TEMP_TIME = 0;
    private static final int TextSize = 40;
    private static final int NumSize = 50;
    private static final int tempTextSize = 50;
    private static final int tempNumSize = 60;

    @InjectView(R.id.title)
    TextView title;
    @InjectView(R.id.toolbar)
    Toolbar toolbar;
    @InjectView(R.id.rb_realtemp)
    RadioButton rbRealtemp;
    @InjectView(R.id.rb_tds)
    RadioButton rbTds;
    @InjectView(R.id.rg_switch)
    RadioGroup rgSwitch;
    @InjectView(R.id.iv_setting)
    ImageView ivSetting;
    @InjectView(R.id.tdsDetailProgress)
    TdsDetailProgress tdsDetailProgress;
    @InjectView(R.id.iv_tdsState)
    ImageView ivTdsState;
    @InjectView(R.id.tv_tdsState)
    TextView tvTdsState;
    @InjectView(R.id.tv_tdsValue)
    TextView tvTdsValue;
    @InjectView(R.id.rlay_back)
    RelativeLayout rlayBack;
    @InjectView(R.id.tv_tempValue)
    TextView tvTempValue;
    @InjectView(R.id.tv_tempUtil)
    TextView tvTempUtil;
    @InjectView(R.id.tv_tempDec)
    TextView tvTempDec;
    @InjectView(R.id.rlay_font)
    RelativeLayout rlayFont;
    @InjectView(R.id.rlay_flip)
    RelativeLayout rlayFlip;
    @InjectView(R.id.tb_switch)
    ToggleButton tbSwitch;
    @InjectView(R.id.tv_advance_time)
    TextView tvAdvanceTime;
    @InjectView(R.id.iv_coffee)
    ImageView ivCoffee;
    @InjectView(R.id.tv_coffee)
    TextView tvCoffee;
    @InjectView(R.id.iv_tea)
    ImageView ivTea;
    @InjectView(R.id.tv_tea)
    TextView tvTea;
    @InjectView(R.id.iv_flour)
    ImageView ivFlour;
    @InjectView(R.id.tv_flour)
    TextView tvFlour;
    @InjectView(R.id.iv_milk)
    ImageView ivMilk;
    @InjectView(R.id.tv_milk)
    TextView tvMilk;
    @InjectView(R.id.iv_custom)
    ImageView ivCustom;
    @InjectView(R.id.tv_custom)
    TextView tvCustom;
    @InjectView(R.id.tv_mode_bolling)
    TextView tvModeBolling;
    @InjectView(R.id.tv_mode_heating)
    TextView tvModeHeating;
    @InjectView(R.id.tv_preservation_tips)
    TextView tvPreservationTips;
    @InjectView(R.id.sb_preservation_time)
    SeekBar sbPreservationTime;
    @InjectView(R.id.tv_preservation_temp_tips)
    TextView tvPreservationTempTips;
    @InjectView(R.id.uizsb_preservation_temp)
    UIZSeekBarNormal uizsbPreservationTemp;

    private int curCheckState = R.id.rb_realtemp;
    private Calendar advanceCal;
    private Kettle mKettle;
    private OznerDeviceSettings oznerSetting;
    private String mUserid;

    ScaleAnimation scaleBigAnimator, scaleSmallAnimator;
    private int lastSelectPervation = -1;//上次选中的保温温度
    private KettleMonitor mMonitor;
    private boolean isTimePickerShow = false;
    //    private TimePicker timePicker;
    private LinkagePicker linkPicker;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLER_TEMP_TIME:
                    tvPreservationTips.setText(String.format(Locale.getDefault()
                            , getString(R.string.kettle_sustain_time), sbPreservationTime.getProgress() / 10.f));
                    break;
            }
            super.handleMessage(msg);
        }
    };

    public KettleFragment() {
        // Required empty public constructor
    }

    private void saveCustomerValue(int value, String mac) {
        Log.e(TAG, "saveCustomerValue: " + value);

        UserDataPreference.SetUserData(getContext(), CUSTOMER_TEMP + mac, String.valueOf(value));
    }

    private int getCustomerValue(String mac) {
        String value = UserDataPreference.GetUserData(getContext(), CUSTOMER_TEMP + mac, "0");
        Log.e(TAG, "getCustomerValue: " + value);
        try {
            return Integer.parseInt(value);
        } catch (Exception ex) {
            return 0;
        }
    }

    /**
     * 注册广播监听
     */
    private void registerMonitor() {
        mMonitor = new KettleMonitor();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BaseDeviceIO.ACTION_DEVICE_CONNECTED);
        filter.addAction(BaseDeviceIO.ACTION_DEVICE_CONNECTING);
        filter.addAction(BaseDeviceIO.ACTION_DEVICE_DISCONNECTED);
        filter.addAction(OznerDeviceManager.ACTION_OZNER_MANAGER_DEVICE_CHANGE);
        filter.addAction(Kettle.ACTION_BLUETOOTH_KETTLE_SENSOR);
        getContext().registerReceiver(mMonitor, filter);
    }

    /**
     * 注销广播监听
     */
    private void releaseMonitor() {
        if (isAdded()) {
            getContext().unregisterReceiver(mMonitor);
        }
    }


    /**
     * 实例化Fragment
     *
     * @param mac
     *
     * @return
     */
    public static DeviceFragment newInstance(String mac) {
        Log.e(TAG, "newInstance: " + mac);
        KettleFragment fragment = new KettleFragment();
        Bundle bundle = new Bundle();
        bundle.putString(DeviceAddress, mac);
        if (bundle != null) {
            fragment.setArguments(bundle);
        }

        return fragment;
    }

    @Override
    public void setDevice(OznerDevice device) {
        oznerSetting = DBManager.getInstance(getContext()).getDeviceSettings(mUserid, device.Address());
        Log.e(TAG, "setDevice: OznerSetting:" + oznerSetting.toString());
        if (mKettle != null) {
            if (mKettle.Address().equals(device.Address())) {
                mKettle = null;
                mKettle = (Kettle) device;
                refreshUIData();
            }
            Log.e(TAG, "setDevice: " + mKettle.status().toString());
        } else {
            mKettle = (Kettle) device;
            Log.e(TAG, "setDevice: " + mKettle.status().toString());
            refreshUIData();
        }
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUserid = OznerPreference.GetValue(getContext(), OznerPreference.UserId, "");
        initScaleAnimator();
//        initAnimation();
        try {
            Bundle bundle = getArguments();
            mKettle = (Kettle) OznerDeviceManager.Instance().getDevice(bundle.getString(DeviceAddress));
            oznerSetting = DBManager.getInstance(getContext()).getDeviceSettings(mUserid, mKettle.Address());
            refreshUIData();
        } catch (Exception ex) {
            ex.printStackTrace();
            LCLogUtils.E(TAG, "onCreate_Ex: " + ex.getMessage());
        }
    }

    private void initLinkPicker() {
        linkPicker = new LinkagePicker(getActivity(), new MyLinkageTimeProvider());
        linkPicker.setCycleDisable(true);
        linkPicker.setLabel("", getString(R.string.kettle_hour), getString(R.string.kettle_minute));
        linkPicker.setOnStringPickListener(new LinkagePicker.OnStringPickListener() {
            @Override
            public void onPicked(String first, String second, String third) {
                Log.e(TAG, "onPicked: " + first + " ," + second + ":" + third);
                int hour = Integer.parseInt(second);
                int minute = Integer.parseInt(third);
                Calendar curCal = Calendar.getInstance();
                advanceCal = Calendar.getInstance();
                if (first.equals(getString(R.string.tomorrow))) {
                    advanceCal.add(Calendar.DAY_OF_MONTH, 1);
                }

                advanceCal.set(Calendar.HOUR_OF_DAY, hour);
                advanceCal.set(Calendar.MINUTE, minute);

                if (advanceCal.getTimeInMillis() < curCal.getTimeInMillis()) {
                    hour = curCal.get(Calendar.HOUR_OF_DAY);
                    minute = curCal.get(Calendar.MINUTE) + 1;
                    if (hour < 10) {
                        second = "0" + hour;
                    }
                    if (minute < 10) {
                        third = "0" + minute;
                    }
                }

                tvAdvanceTime.setText(String.format(Locale.getDefault(), "%s  %s:%s", first, second, third));
                long timeInterval = (advanceCal.getTimeInMillis() - curCal.getTimeInMillis()) / 1000;
                mKettle.setPreservationTime((int) timeInterval, mOperateCallback);
                isTimePickerShow = false;
            }
        });
    }

    private void initScaleAnimator() {
        scaleBigAnimator = new ScaleAnimation(1.0f, 1.2f, 1.0f, 1.2f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleBigAnimator.setDuration(100);
        scaleBigAnimator.setFillAfter(true);

        scaleSmallAnimator = new ScaleAnimation(1.2f, 1.0f, 1.2f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleSmallAnimator.setDuration(100);
        scaleSmallAnimator.setFillAfter(true);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        ((MainActivity) getActivity()).initActionBarToggle(toolbar);
        super.onActivityCreated(savedInstanceState);

        initSeekBarChange();
        tbSwitch.setOnToggleChanged(new ToggleButton.OnToggleChanged() {
            @Override
            public void onToggle(boolean b) {
                mKettle.enableAdvance(b, mOperateCallback);
                Log.e(TAG, "onToggle: " + b);
                if (b) {
                    if (tvAdvanceTime.getVisibility() != View.VISIBLE) {
                        showTimewPicker();
                        tvAdvanceTime.setVisibility(View.VISIBLE);
                    }
                } else {
                    tvAdvanceTime.setVisibility(View.GONE);
                }

            }
        });
        setCameraDistance();
        rgSwitch.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.rb_realtemp:
                        if (curCheckState != checkedId) {
                            curCheckState = R.id.rb_realtemp;
                            showRealTempView();
                        }
                        break;
                    case R.id.rb_tds:
                        if (curCheckState != checkedId) {
                            curCheckState = R.id.rb_tds;
                            showTdsView();
                        }
                        break;
                }
            }
        });
//        initTimepicker();
        initLinkPicker();

    }

    private void initSeekBarChange() {
        uizsbPreservationTemp.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    selectPrevation(4, lastSelectPervation);
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    Log.e(TAG, "onTouch: 保温温度：" + uizsbPreservationTemp.getProgress());
                    if (mKettle != null) {
                        saveCustomerValue(uizsbPreservationTemp.getProgress(), mKettle.Address());
                        mKettle.setPreservationTemperature(uizsbPreservationTemp.getProgress(), mOperateCallback);
                    }
                }
                return false;
            }
        });

        sbPreservationTime.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    tvPreservationTips.setText(String.format(Locale.getDefault()
                            , getString(R.string.kettle_sustain_time), sbPreservationTime.getProgress() / 10.f));
                    if (mKettle != null)
                        mKettle.setPreservationTime((sbPreservationTime.getProgress() * 6), mOperateCallback);
                }
                return false;
            }
        });

        sbPreservationTime.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mHandler.sendEmptyMessage(HANDLER_TEMP_TIME);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_kettle, container, false);
        ButterKnife.inject(this, view);
        toolbar.setTitle("");
        ((MainActivity) getActivity()).setSupportActionBar(toolbar);
        return view;
    }

    private void scaleView(View view, boolean isBig) {
        if (isBig) {
            view.startAnimation(scaleBigAnimator);
        } else {
            view.startAnimation(scaleSmallAnimator);
        }
    }


//    private void initTimepicker() {
//        timePicker = new TimePicker(getActivity(), TimePicker.HOUR_24);
//        timePicker.setRangeStart(0, 0);
//        timePicker.setRangeEnd(23, 59);
//        int currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
//        int currentMinute = Calendar.getInstance().get(Calendar.MINUTE);
//        timePicker.setSelectedItem(currentHour, currentMinute);
//        timePicker.setDividerColor(0xffffff);
//        timePicker.setLabel(getString(R.string.kettle_hour), getString(R.string.kettle_minute));
//        timePicker.setTextColor(ContextCompat.getColor(getContext(), R.color.black_deep));
//        timePicker.setTopLineVisible(false);
//        timePicker.setCancelTextColor(ContextCompat.getColor(getContext(), R.color.black_deep));
//        timePicker.setSubmitTextColor(ContextCompat.getColor(getContext(), R.color.black_deep));
//        timePicker.setAnimationStyle(R.style.AnimBottom);
//        timePicker.setOnTimePickListener(new TimePicker.OnTimePickListener() {
//            @Override
//            public void onTimePicked(String hour, String minute) {
//                Log.e(TAG, "onTimePicked: " + hour + ":" + minute);
//                tvAdvanceTime.setText(hour + ":" + minute);
//                int iHour = Integer.parseInt(hour);
//                int iMinute = Integer.parseInt(minute);
//
//                Calendar curCal = Calendar.getInstance();
//                advanceCal = Calendar.getInstance();
//                advanceCal.set(Calendar.HOUR_OF_DAY, iHour);
//                advanceCal.set(Calendar.MINUTE, iMinute);
//                //预约时间在当前时间之前，设置的是明天
//                if (advanceCal.getTimeInMillis() < curCal.getTimeInMillis()) {
//                    advanceCal.add(Calendar.DAY_OF_MONTH, 1);
//                }
//
//                long timeInterval = (advanceCal.getTimeInMillis() - curCal.getTimeInMillis()) / 1000;
//
//                mKettle.setPreservationTime((int) timeInterval, mOperateCallback);
//                isTimePickerShow = false;
//            }
//        });
//    }

    private void showTimewPicker() {

//        linkPicker.setSelectedIndex(0, Calendar.getInstance().get(Calendar.HOUR_OF_DAY), Calendar.getInstance().get(Calendar.MINUTE));
        linkPicker.show();
        isTimePickerShow = true;
    }

    /**
     * 改变视角距离, 贴近屏幕
     */
    private void setCameraDistance() {
        int distance = 10000;
        float scale = getResources().getDisplayMetrics().density * distance;
        rlayFlip.setCameraDistance(scale);
    }

    private void showRealTempView() {
        Rotatable rotatable = new Rotatable.Builder(rlayFlip)
                .sides(R.id.rlay_font, R.id.rlay_back)
                .direction(Rotatable.ROTATE_Y)
                .rotationCount(1)
                .build();
        rotatable.setTouchEnable(false);
        rotatable.rotate(Rotatable.ROTATE_Y, 0, 1000);
    }

    private void showTdsView() {
        Rotatable rotatable = new Rotatable.Builder(rlayFlip)
                .sides(R.id.rlay_font, R.id.rlay_back)
                .direction(Rotatable.ROTATE_Y)
                .rotationCount(1)
                .build();
        rotatable.setTouchEnable(false);
        rotatable.rotate(Rotatable.ROTATE_Y, -180, 1000);
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            setBarColor(R.color.cup_detail_bg);
            setToolbarColor(R.color.cup_detail_bg);
            if (oznerSetting != null) {
                title.setText(oznerSetting.getName());
            } else {
                title.setText(R.string.kettle_name);
            }
        } catch (Exception ex) {
            Log.e(TAG, "onResume_Ex: " + ex.getMessage());
        }
        registerMonitor();
    }


    @Override
    public void onPause() {
        releaseMonitor();
        super.onPause();
    }

    /**
     * 设置toolbar背景色
     *
     * @param resId
     */
    protected void setToolbarColor(int resId) {
        if (isThisAdd())
            toolbar.setBackgroundColor(ContextCompat.getColor(getContext(), resId));
    }

    private boolean isThisAdd() {
        return KettleFragment.this.isAdded() && !KettleFragment.this.isRemoving();
    }

    @Override
    public void onDetach() {
        System.gc();
        super.onDetach();
    }


    @Override
    protected void refreshUIData() {
        if (isAdded() && mKettle != null) {
            if (oznerSetting != null && !TextUtils.isEmpty(oznerSetting.getName())) {
                title.setText(oznerSetting.getName());
            } else {
                title.setText(mKettle.getName());
            }
            Log.e(TAG, "refreshUIData: " + mKettle.connectStatus());
            if (mKettle != null && mKettle.connectStatus() == BaseDeviceIO.ConnectStatus.Connected) {
                refreshSensorData();
            } else {
                loadTdsNoData();
                showSensorEmpty();
                if (mKettle.connectStatus() == BaseDeviceIO.ConnectStatus.Disconnect) {
                    tvTempDec.setText(R.string.device_unconnected);
                } else {
                    tvTempDec.setText(R.string.device_connecting);
                }
            }
        }
    }

    private void showSensorEmpty() {
        tbSwitch.setToggleOff();
        tvAdvanceTime.setText("00:00");
        setPreservationTime(0);
        showPreservationMode(PreservationMode.None);
        showPerservationTemp(0);
        tvTempUtil.setVisibility(View.GONE);
        tvTempValue.setText(R.string.state_null);
        tvTempValue.setTextSize(tempTextSize);
        tvPreservationTempTips.setText(String.format(Locale.getDefault(),getString(R.string.kettle_sustain_time),0f));
    }


    /**
     * 刷新传感器数据
     */
    private void refreshSensorData() {
        if (!isTimePickerShow) {
            if (mKettle.status().reservation) {
                tvAdvanceTime.setVisibility(View.VISIBLE);
                tbSwitch.setToggleOn();

            } else {
                tvAdvanceTime.setVisibility(View.GONE);
                tbSwitch.setToggleOff();
            }
        }

        int hour = mKettle.status().reservationTime / 60;
        int minute = mKettle.status().reservationTime % 60;

        advanceCal = Calendar.getInstance();
        advanceCal.add(Calendar.HOUR_OF_DAY, hour);
        advanceCal.add(Calendar.MINUTE, minute);

        StringBuilder hourSb = new StringBuilder();
        StringBuilder minSb = new StringBuilder();
        hour = advanceCal.get(Calendar.HOUR_OF_DAY);
        minute = advanceCal.get(Calendar.MINUTE);
        if (hour < 10) {
            hourSb.append("0");
        }
        hourSb.append(hour);
        if (minute < 10) {
            minSb.append("0");
        }
        minSb.append(minute);
        tvAdvanceTime.setText(String.format("%s:%s", hourSb.toString(), minSb.toString()));

        showPerservationTemp(mKettle.status().preservationTemperature);
        showPreservationMode(mKettle.status().preservationMode);
        setPreservationTime(mKettle.status().preservationTime);
        showRealTemp(mKettle.status().temperature);
        setHeatMode(mKettle.status().heatMode);
        loadTdsInfo(mKettle.status().TDS);
    }

    private void loadTdsInfo(int tdsValue) {
        if (tdsValue > 5000) {//传感器无数据
            loadTdsNoData();
        } else {
            //显示tds对应状态
            if (tdsValue > 0 && tdsValue <= CupRecord.TDS_Good_Value) {
                ivTdsState.setVisibility(View.VISIBLE);
                Glide.with(this).load(R.drawable.face_good).asBitmap().into(ivTdsState);
                tvTdsState.setText(R.string.health);
            } else if (tdsValue > CupRecord.TDS_Good_Value && tdsValue <= CupRecord.TDS_Bad_Value) {
                ivTdsState.setVisibility(View.VISIBLE);
                Glide.with(this).load(R.drawable.face_soso).asBitmap().into(ivTdsState);
                tvTdsState.setText(R.string.soso);
            } else if (tdsValue > CupRecord.TDS_Bad_Value) {
                ivTdsState.setVisibility(View.VISIBLE);
                Glide.with(this).load(R.drawable.face_bad).asBitmap().into(ivTdsState);
                tvTdsState.setText(R.string.bad);
            }

            //数字跑马灯
            if (tdsValue != 0) {
                tvTdsValue.setTextSize(NumSize);
                tvTdsValue.setText(String.valueOf(tdsValue));
                if (tdsValue > 250) {
                    tdsDetailProgress.update(100);
                } else {
                    tdsDetailProgress.update((tdsValue << 1) / 5);
                }
            } else {
                loadTdsNoData();
            }
        }
    }

    private void loadTdsNoData() {
        tvTdsState.setText(R.string.state_null);
        ivTdsState.setVisibility(View.GONE);
        tvTdsValue.setText(R.string.no_data);
        tvTdsValue.setTextSize(TextSize);
        tdsDetailProgress.update(0);
    }


    /**
     * 加载保温时间
     *
     * @param time
     */
    private void setPreservationTime(float time) {
        Log.e(TAG, "setPreservationTime: " + time / 6);
        sbPreservationTime.setProgress((int) (time / 6.f));
        tvPreservationTips.setText(String.format(Locale.getDefault(), getString(R.string.kettle_sustain_time), time / 60.f));
    }

    /**
     * 加载加热模式
     *
     * @param mode
     */
    private void setHeatMode(HeatMode mode) {
        if (mode.equals(HeatMode.Heating)) {
            tvTempDec.setText(R.string.heating);
        } else if (mode.equals(HeatMode.Idle)) {
            tvTempDec.setText(R.string.kettle_idle);
        } else if (mode.equals(HeatMode.Preservation)) {
            tvTempDec.setText(R.string.keep_warm);
        }
    }

    /**
     * 加载实时温度
     *
     * @param temp
     */
    private void showRealTemp(int temp) {
        tvTempUtil.setVisibility(View.VISIBLE);
        tvTempValue.setTextSize(tempNumSize);
        tvTempValue.setText(String.valueOf(temp));
        int tempColor = WPTempColorUtil.getColor(temp);
        tvTempValue.setTextColor(tempColor);
        tvTempUtil.setTextColor(tempColor);
    }

    /**
     * 加载保温温度
     *
     * @param temp
     */
    private void showPerservationTemp(int temp) {
        Log.e(TAG, "showPerservationTemp: "+temp);
        uizsbPreservationTemp.setProgress(temp);
        switch (temp) {
            case 90:
                selectPrevation(0, lastSelectPervation);
                break;
            case 80:
                selectPrevation(1, lastSelectPervation);
                break;
            case 70:
                selectPrevation(2, lastSelectPervation);
                break;
            case 50:
                selectPrevation(3, lastSelectPervation);
                break;
            default:
                selectPrevation(4, lastSelectPervation);
                //加载以保存的自定义温度
                break;
        }
    }

    /**
     * 加载保温模式
     *
     * @param mode
     */
    private void showPreservationMode(PreservationMode mode) {
        if (PreservationMode.Boiling.equals(mode)) {
            tvModeBolling.setTextColor(ContextCompat.getColor(getContext(), R.color.kettle_preservation_select));
            tvModeHeating.setTextColor(ContextCompat.getColor(getContext(), R.color.kettle_text_disable));
        } else if (PreservationMode.Heating.equals(mode)) {
            tvModeHeating.setTextColor(ContextCompat.getColor(getContext(), R.color.kettle_preservation_select));
            tvModeBolling.setTextColor(ContextCompat.getColor(getContext(), R.color.kettle_text_disable));
        } else {
            tvModeHeating.setTextColor(ContextCompat.getColor(getContext(), R.color.kettle_text_disable));
            tvModeBolling.setTextColor(ContextCompat.getColor(getContext(), R.color.kettle_text_disable));
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    /**
     * 选择保温温度
     *
     * @param currentSelect
     * @param lastSelect
     */
    private void selectPrevation(int currentSelect, int lastSelect) {
        Log.e(TAG, "selectPrevation: " + currentSelect + ",lastSelect:" + lastSelect);
//        if (currentSelect == lastSelect) {
//            return;
//        }
        resetLastSelect(lastSelect);
        switch (currentSelect) {
            case 0:
                tvCoffee.setTextColor(ContextCompat.getColor(getContext(), R.color.kettle_preservation_select));
                scaleView(ivCoffee, true);
                scaleView(tvCoffee, true);
                break;
            case 1:
                tvTea.setTextColor(ContextCompat.getColor(getContext(), R.color.kettle_preservation_select));
                scaleView(ivTea, true);
                scaleView(tvTea, true);
                break;
            case 2:
                tvFlour.setTextColor(ContextCompat.getColor(getContext(), R.color.kettle_preservation_select));
                scaleView(ivFlour, true);
                scaleView(tvFlour, true);
                break;
            case 3:
                tvMilk.setTextColor(ContextCompat.getColor(getContext(), R.color.kettle_preservation_select));
                scaleView(ivMilk, true);
                scaleView(tvMilk, true);
                break;
            case 4:
                tvCustom.setTextColor(ContextCompat.getColor(getContext(), R.color.kettle_preservation_select));
                scaleView(ivCustom, true);
                scaleView(tvCustom, true);
                break;
            default:
                tvCustom.setTextColor(ContextCompat.getColor(getContext(), R.color.kettle_preservation_select));
                scaleView(ivCustom, true);
                scaleView(tvCustom, true);
                break;
        }
        lastSelectPervation = currentSelect;
    }

    /**
     * 重置上次选择
     *
     * @param lastSelect
     */
    private void resetLastSelect(int lastSelect) {
        Log.e(TAG, "resetLastSelect: " + lastSelect);
        switch (lastSelect) {
            case 0:
                tvCoffee.setTextColor(ContextCompat.getColor(getContext(), R.color.kettle_text_disable));
                scaleView(ivCoffee, false);
                scaleView(tvCoffee, false);
                break;
            case 1:
                tvTea.setTextColor(ContextCompat.getColor(getContext(), R.color.kettle_text_disable));
                scaleView(ivTea, false);
                scaleView(tvTea, false);
                break;
            case 2:
                tvFlour.setTextColor(ContextCompat.getColor(getContext(), R.color.kettle_text_disable));
                scaleView(ivFlour, false);
                scaleView(tvFlour, false);
                break;
            case 3:
                tvMilk.setTextColor(ContextCompat.getColor(getContext(), R.color.kettle_text_disable));
                scaleView(ivMilk, false);
                scaleView(tvMilk, false);
                break;
            case 4:
                tvCustom.setTextColor(ContextCompat.getColor(getContext(), R.color.kettle_text_disable));
                scaleView(ivCustom, false);
                scaleView(tvCustom, false);
                break;
            default:
                tvCustom.setTextColor(ContextCompat.getColor(getContext(), R.color.kettle_text_disable));
                scaleView(ivCustom, false);
                scaleView(tvCustom, false);
                break;
        }
    }

    @OnClick({R.id.llay_coffee, R.id.llay_tea, R.id.llay_flour, R.id.llay_milk, R.id.llay_custom,
            R.id.iv_setting, R.id.tv_advance_time
            , R.id.llay_mode_bolling, R.id.llay_mode_heating})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_setting:
                if (mKettle != null) {
                    Intent setIntent = new Intent(getContext(), SetUpKettleActivity.class);
                    setIntent.putExtra(Contacts.PARMS_MAC, mKettle.Address());
                    startActivity(setIntent);
                } else {
                    Toast.makeText(getContext(), R.string.Not_found_device, Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.tv_advance_time:
                showTimewPicker();
                break;
            case R.id.llay_coffee:
                uizsbPreservationTemp.setProgress(90);
                selectPrevation(0, lastSelectPervation);
                try {
                    mKettle.setPreservationTemperature(90, mOperateCallback);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    Log.e(TAG, "llay_coffee_Ex: " + ex.getMessage());
                }
                break;
            case R.id.llay_tea:
                uizsbPreservationTemp.setProgress(80);
                selectPrevation(1, lastSelectPervation);
                try {
                    mKettle.setPreservationTemperature(80, mOperateCallback);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    Log.e(TAG, "llay_tea_Ex: " + ex.getMessage());
                }
                break;
            case R.id.llay_flour:
                uizsbPreservationTemp.setProgress(70);
                selectPrevation(2, lastSelectPervation);
                try {
                    mKettle.setPreservationTemperature(70, mOperateCallback);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    Log.e(TAG, "llay_flour_Ex: " + ex.getMessage());
                }
                break;
            case R.id.llay_milk:
                uizsbPreservationTemp.setProgress(50);
                selectPrevation(3, lastSelectPervation);
                try {
                    mKettle.setPreservationTemperature(50, mOperateCallback);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    Log.e(TAG, "llay_milk_Ex: " + ex.getMessage());
                }
                break;
            case R.id.llay_custom:
                uizsbPreservationTemp.setProgress(getCustomerValue(mKettle.Address()));
                selectPrevation(4, lastSelectPervation);
                try {
                    mKettle.setPreservationTemperature(getCustomerValue(mKettle.Address()), mOperateCallback);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    Log.e(TAG, "llay_custom_Ex: " + ex.getMessage());
                }
                break;
            case R.id.llay_mode_bolling:
                try {
                    mKettle.setPreservationMode(PreservationMode.Boiling, mOperateCallback);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    Log.e(TAG, "llay_mode_bolling_Ex: " + ex.getMessage());
                }
                break;
            case R.id.llay_mode_heating:
                mKettle.setPreservationMode(PreservationMode.Heating, mOperateCallback);
                break;
        }
    }

    class MyLinkageTimeProvider extends LinkagePicker.DataProvider {

        @NonNull
        @Override
        public List<String> provideFirstData() {
            ArrayList<String> first = new ArrayList<>();
            first.add(getString(R.string.today));
            first.add(getString(R.string.tomorrow));
            return first;
        }

        @NonNull
        @Override
        public List<String> provideSecondData(int firstIndex) {
            ArrayList<String> second = new ArrayList<>();
            if (firstIndex == 0) {
                int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
                for (int i = hour; i < 24; i++) {
                    if (i < 10) {
                        second.add(String.format(Locale.getDefault(), "0%d", i));
                    } else {
                        second.add(String.valueOf(i));
                    }
                }
            } else {
                for (int i = 0; i < 24; i++) {
                    if (i < 10) {
                        second.add(String.format(Locale.getDefault(), "0%d", i));
                    } else {
                        second.add(String.valueOf(i));
                    }
                }
            }
            return second;
        }

        @Nullable
        @Override
        public List<String> provideThirdData(int firstIndex, int secondIndex) {
            ArrayList<String> third = new ArrayList<>();
            for (int i = 0; i < 60; i++) {
                if (i < 10) {
                    third.add("0" + i);
                } else {
                    third.add(String.valueOf(i));
                }
            }
            return third;
        }

        @Override
        public boolean isOnlyTwo() {
            return false;
        }
    }

    class KettleMonitor extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e(TAG, "onReceive: " + intent.getAction());
            refreshUIData();
        }
    }

    public OperateCallback mOperateCallback = new OperateCallback<Void>() {

        @Override
        public void onSuccess(Void var1) {
            Log.e(TAG, "onSuccess: 发送成功");

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getContext(), getString(R.string.send_status_success), Toast.LENGTH_SHORT).show();
                }
            });
        }

        @Override
        public void onFailure(Throwable var1) {
            Log.e(TAG, "onFailure: 发送失败");

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getContext(), getString(R.string.send_status_fail), Toast.LENGTH_SHORT).show();
                }
            });
        }
    };
}
